﻿
/// <reference path="jquery-1.4.4-vsdoc.js" />
/// <reference path="jquery.validate-vsdoc.js" />
/// <reference path="hoverIntent.js" />

(function ($) {
    $.extend({
        Nasa8x: {
            minutePageRefresh: 0,
            prefix: 'Nasa8x_',
            loadingId: '#_loading',
            ajaxContainer: '#_ajaxContainer',
            fileManagerUrl: '/FlexExplorer/',
            imagePrefix: 'http://localhost:8191/Img.ashx?',
            cookieDays: 30,
            messages: {},

            ReCaptcha: {
                publicKey: '6LfV3MISAAAAAMfrkyDzhYZNkjR3YlyOC_YlIfn_',
                theme: 'red',
                create: function (placeHolder) {
                    Recaptcha.create(this.publicKey, placeHolder, {
                        theme: "red"
                        //,callback: Recaptcha.focus_response_field
                    });

                }

            },


            Cookie: {
                cookie: function (key, value, options) {

                    // key and at least value given, set cookie...
                    //https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
                    /** @example $.cookie('the_cookie', 'the_value');
                    * @desc Set the value of a cookie.
                    * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
                    * @desc Create a cookie with all available options.
                    * @example $.cookie('the_cookie', 'the_value');
                    * @desc Create a session cookie.
                    * @example $.cookie('the_cookie', null);
                    * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
                    * used when the cookie was set.
                    */
                    // key and at least value given, set cookie...
                    if (arguments.length > 1 && String(value) !== "[object Object]") {
                        options = jQuery.extend({}, options);

                        if (value === null || value === undefined) {
                            options.expires = -1;
                        }

                        if (typeof options.expires === 'number') {
                            var days = options.expires, t = options.expires = new Date();
                            t.setDate(t.getDate() + days);
                        }

                        value = String(value);

                        return (document.cookie = [
                            encodeURIComponent(key), '=',
                            options.raw ? value : encodeURIComponent(value),
                            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                            options.path ? '; path=' + options.path : '; path=/',
                            options.domain ? '; domain=' + options.domain : '; domain=' + document.domain,
                            options.secure ? '; secure' : ''
                        ].join(''));
                    }

                    // key and possibly options given, get cookie...
                    options = value || {};
                    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
                    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
                },
                add: function (key, value, options) {
                    this.cookie(key, value, options);

                },
                get: function (key) {

                    return this.cookie(key);

                },
                remove: function (key) {
                    this.cookie(key, null);

                }

            },

            String: {
                trim: function () {
                    return this.replace(/^\s+|\s+$/g, '');

                },

                //if( $.StringEx.isNullOrEmpty('') ) alert('Empty string');
                isNullOrEmpty: function (value) {
                    if (value) {
                        if (typeof (value) == 'string') {
                            if (value.length > 0)
                                return false;
                        }
                        if (value != null)
                            return false;
                    }
                    return true;

                },

                replace: function (source, oldVal, newVal) {
                    var result = source;
                    result = result.replace(oldVal, newVal);
                    //result = result.replace(new RegExp(oldVal, 'ig'), newVal);
                    //result = result.replace(new RegExp('\\' + oldVal + '\\', 'g'), newVal);

                    return result;
                },

                //alert( $.StringEx.format("Hello {0}.","Nasa8x") );
                format: function (format, args) {
                    var result = format;
                    for (var i = 1; i < arguments.length; i++) {
                        result = result.replace(new RegExp('\\{' + (i - 1) + '\\}', 'g'), arguments[i]);
                    }
                    return result;
                },
                startsWith: function (prefix, ignoreCase) {
                    if (!prefix) return false;
                    if (prefix.length > this.length) return false;
                    if (ignoreCase) {
                        if (ignoreCase == true) {
                            return (this.substr(0, prefix.length).toUpperCase() == prefix.toUpperCase());
                        }
                    }
                    return (this.substr(0, prefix.length) === prefix);
                },
                endsWith: function (suffix, ignoreCase) {
                    if (!suffix) return false;
                    if (suffix.length > this.length) return false;
                    if (ignoreCase) {
                        if (ignoreCase == true) {
                            return (this.substr(this.length - suffix.length).toUpperCase() == suffix.toUpperCase());
                        }
                    }
                    return (this.substr(this.length - suffix.length) === suffix);
                }
            },


            Fx: {

                baseUrl: '/flexexplorer/',

                defaults: {
                    callback: null
                },


                render: function (opts) {

                    var _imgs = opts.files.split(';');

                    var _imgPanel = $(opts.targetId);

                    $.each(_imgs, function (index, value) {

                        var _id = value.replace(".", "_").replace("/", "_");

                        if ($('#_img_' + _id).length == 0) {
                            var _html = '<li onmouseover="$(\'#_action_img_' + _id + '\').show();" onmouseout="$(\'#_action_img_' + _id + '\').hide();" class="rc img-thumb" id="_img_' + _id + '"><div>';
                            _html += '<input type="hidden" name="img" value="' + value + '" />';
                            _html += '<img class="thumb-50" src="' + $.Nasa8x.imagePrefix + value + '&size=50" />';
                            _html += '<div id="_action_img_' + _id + '" class="action"><a href="javascript:void(0)" class="icon-16 ok" title="Chọn là ảnh chính" onclick="$.Nasa8x.moveFirst(\'#_img_' + _id + '\',\'#_imagePreview\');" >&nbsp;</a><a href="javascript:void(0)" title="Xóa ảnh này" class="icon-16 del" onclick="$.Nasa8x.remove(\'#_img_' + _id + '\');" >&nbsp;</a></div>';
                            _html += '</div></li>';

                            _imgPanel.append(_html);
                        }

                    });

                    _imgPanel.show();

                },
                open: function (opts) {

                    var url = this.baseUrl + '?fx=1';

                    var w = opts.width > 0 ? opts.width : screen.width * 0.8;
                    var h = opts.height > 0 ? opts.height : screen.height * 0.8;

                    var winX = ($(window).width() - w) * .5;
                    var winY = ($(window).height() - h) * .5;

                    //

                    window.showModalDialog(url, opts, 'dialogWidth=' + w + ',dialogHeight=' + h + ',center=yes,left=' + winX + ',top=' + winY);

                }


            },

            Hash: {

                sha256: function (plainText) {

                    var chrsz = 8;
                    var hexcase = 0;

                    function safe_add(x, y) {
                        var lsw = (x & 0xFFFF) + (y & 0xFFFF);
                        var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
                        return (msw << 16) | (lsw & 0xFFFF);
                    }

                    function S(X, n) { return (X >>> n) | (X << (32 - n)); }
                    function R(X, n) { return (X >>> n); }
                    function Ch(x, y, z) { return ((x & y) ^ ((~x) & z)); }
                    function Maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }
                    function Sigma0256(x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); }
                    function Sigma1256(x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); }
                    function Gamma0256(x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); }
                    function Gamma1256(x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); }

                    function core_sha256(m, l) {
                        var K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2);
                        var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);
                        var W = new Array(64);
                        var a, b, c, d, e, f, g, h;
                        var T1, T2;

                        m[l >> 5] |= 0x80 << (24 - l % 32);
                        m[((l + 64 >> 9) << 4) + 15] = l;

                        for (var i = 0; i < m.length; i += 16) {
                            a = HASH[0];
                            b = HASH[1];
                            c = HASH[2];
                            d = HASH[3];
                            e = HASH[4];
                            f = HASH[5];
                            g = HASH[6];
                            h = HASH[7];

                            for (var j = 0; j < 64; j++) {
                                if (j < 16) W[j] = m[j + i];
                                else W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);

                                T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
                                T2 = safe_add(Sigma0256(a), Maj(a, b, c));

                                h = g;
                                g = f;
                                f = e;
                                e = safe_add(d, T1);
                                d = c;
                                c = b;
                                b = a;
                                a = safe_add(T1, T2);
                            }

                            HASH[0] = safe_add(a, HASH[0]);
                            HASH[1] = safe_add(b, HASH[1]);
                            HASH[2] = safe_add(c, HASH[2]);
                            HASH[3] = safe_add(d, HASH[3]);
                            HASH[4] = safe_add(e, HASH[4]);
                            HASH[5] = safe_add(f, HASH[5]);
                            HASH[6] = safe_add(g, HASH[6]);
                            HASH[7] = safe_add(h, HASH[7]);
                        }
                        return HASH;
                    }

                    function str2binb(str) {
                        var bin = Array();
                        var mask = (1 << chrsz) - 1;
                        for (var i = 0; i < str.length * chrsz; i += chrsz) {
                            bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
                        }
                        return bin;
                    }

                    function Utf8Encode(string) {
                        string = string.replace(/\r\n/g, "\n");
                        var utftext = "";

                        for (var n = 0; n < string.length; n++) {

                            var c = string.charCodeAt(n);

                            if (c < 128) {
                                utftext += String.fromCharCode(c);
                            }
                            else if ((c > 127) && (c < 2048)) {
                                utftext += String.fromCharCode((c >> 6) | 192);
                                utftext += String.fromCharCode((c & 63) | 128);
                            }
                            else {
                                utftext += String.fromCharCode((c >> 12) | 224);
                                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                                utftext += String.fromCharCode((c & 63) | 128);
                            }

                        }

                        return utftext;
                    }

                    function binb2hex(binarray) {
                        var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
                        var str = "";
                        for (var i = 0; i < binarray.length * 4; i++) {
                            str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
                        }
                        return str;
                    }

                    plainText = Utf8Encode(plainText);
                    return binb2hex(core_sha256(str2binb(plainText), plainText.length * chrsz));
                }


            },

            Environment: {
                idleTime: 0,
                standby: false,

                setStandBy: function () {
                    if (!this.standby) {

                        $("body").append('<div id="energysaving"><p>Chế độ tiết kiệm năng lượng<br /><span>Di chuyển chuột để trở lại trang hiện tại.</span></p></div>');

                        var _h = $(document).height();
                        $("#energysaving")
                        .css({
                            width: "100%", height: _h, left: "0", top: "0"
                        }).fadeIn()
                        .bind("mousemove keypress", function (e) {
                            $.Nasa8x.Environment.stopStandBy();
                        });

                        $(window).animate({ scrollTop: 0 }, 300);
                        this.standby = true;
                    }
                },


                stopStandBy: function () {
                    if (this.standby) {
                        $("#energysaving").fadeOut(1500, function () {
                            $(this).remove();
                        });

                        this.standby = false;
                    };

                    this.idleTime = 0;
                },
                checkActivity: function () {

                    this.idleTime += 10;
                    //$('#_test').text(this.idleTime);

                    if (this.idleTime > 60) {
                        this.setStandBy();
                    }


                },

                init: function () {

                    $(document).bind('click keypress mousemove', function (event) {
                        $.Nasa8x.Environment.stopStandBy();

                    });

                    setInterval("$.Nasa8x.Environment.checkActivity();", 100000);


                }


            },

            DropDown: {
                configs: {
                    timeout: 500,
                    sensitivity: 7,
                    interval: 100,
                    itemHoverClass: 'top-item-hover',
                    subItemHoverClass: 'top-sub-item-hover'
                },

                create: function (select, options) {

                    $.extend(this.configs, options ? options : {});
                    $(select).hoverIntent({
                        timeout: 500,
                        over: function () {

                            var _this = $(this);
                            _this.addClass($.Nasa8x.DropDown.configs.itemHoverClass);

                            var _sub = $('ul:eq(0)', this);

                            _sub.find("li").hover(
                                    function () {

                                        $(this).addClass($.Nasa8x.DropDown.configs.subItemHoverClass);
                                    },
                                    function () {
                                        $(this).removeClass($.Nasa8x.DropDown.configs.subItemHoverClass);
                                    });

                            _sub.fadeIn();

                        },
                        out: function () {

                            var _this = $(this);

                            _this.removeClass($.Nasa8x.DropDown.configs.itemHoverClass);

                            $('ul:eq(0)', this).hide();

                        }
                    });
                }


            },

            Html: {
                encode: function (_html) {
                    _html = _html.replace(/&quot;/g, '&quotx;');
                    _html = _html.replace(/"/g, '&quot;');
                    _html = _html.replace(/&amp;/g, '&ampx;');
                    _html = _html.replace(/&/g, '&amp;');
                    _html = _html.replace(/&lt;/g, '&ltx;');
                    _html = _html.replace(/</g, '&lt;');
                    _html = _html.replace(/&gt;/g, '&gtx;');
                    _html = _html.replace(/>/g, '&gt;');
                    return _html;
                },
                democde: function (html) {
                    html = html.replace(/&gt;/g, '>');
                    html = html.replace(/&gtx;/g, '&gt;');
                    html = html.replace(/&lt;/g, '<');
                    html = html.replace(/&ltx;/g, '&lt;');
                    html = html.replace(/&amp;/g, '&');
                    html = html.replace(/&ampx;/g, '&amp;');
                    html = html.replace(/&quot;/g, '"');
                    html = html.replace(/&quotx;/g, '&quot;');
                    return html;
                }
            },


            _undefined: function () {
                for (var i = 0; i < arguments.length; i++)
                    if (typeof arguments[i] != 'undefined') return false;
                return true;
            },


            _viewport: function () {
                var d = document.documentElement, b = document.body, w = window;
                return jQuery.extend(
                    jQuery.browser.msie ?
                        { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop} :
                        { left: w.pageXOffset, top: w.pageYOffset },
                    !this._undefined(w.innerWidth) ?
                        { width: w.innerWidth, height: w.innerHeight} :
                        (!this._undefined(d) && !this._undefined(d.clientWidth) && d.clientWidth != 0 ?
                            { width: d.clientWidth, height: d.clientHeight} :
                            { width: b.clientWidth, height: b.clientHeight }));
            },
            _overlay: function (status, callback) {
                switch (status) {
                    case 'show':
                        $("body").append('<div class="overlay" ondblclick="$.Nasa8x.hideLoading()" id="_overlay"></div>');
                        $("#_overlay").css({
                            opacity: 0.2,
                            height: $(document).height()

                        }).fadeIn(500, function () {
                            if ($.isFunction(callback))
                                callback.apply();
                        });
                        break;
                    case 'hide':
                        $('#_overlay').fadeOut('fast', function () {
                            $("#_overlay").remove();
                            if ($.isFunction(callback))
                                callback.apply();

                        });

                        break;
                }
            },


            showLoading: function (sender, args) {
                this._overlay('show');
                var _loading = $(this.loadingId);
                if (_loading.attr("rel") != "centered") {

                    var _v = this._viewport();
                    var _left = (_v.width - $($.Nasa8x.loadingId).outerWidth()) / 2;
                    var _top = _v.top + (_v.height - $($.Nasa8x.loadingId).outerHeight()) / 2;
                    _loading.attr("rel", "centered").css({ top: _top, left: _left });
                };
                _loading.show();



            },
            hideLoading: function (sender, args) {
                $(this.loadingId).fadeOut(100, function () {

                    $.Nasa8x._overlay('hide');

                });

            },


            toggleCheckbox: function (_state, _forClass) {

                // default
                var _class = 'input.item-selected';

                if (_forClass) _class = _forClass;

                $(_class).each(function () {
                    $(this).attr("checked", _state);
                });

            },
            getSelectedItems: function (_forClass) {
                var _items = new Array();

                var _class = 'input.item-selected';

                if (_forClass) _class = _forClass;
                // $("input[@class='item-selected']:checked").each(function() {
                $(_class).each(function () {
                    //if ($(this).attr("checked") == true) {
                    if ($(this).is(":checked")) {
                        _items.push($(this).val());
                    }
                });
                return _items;

            },

            deleteConfirm: function (callback) {
                var _selectedItems = this.getSelectedItems();
                if (_selectedItems > 0) {
                    Confirm($.Nasa8x.String.format($.Nasa8x.messages.deleteItemsConfirm, _selectedItems), null, function (r) {
                        if (r) {
                            if ($.isFunction(callback)) {
                                callback.apply();
                            }
                        }


                    });
                }
                else {
                    Alert($.Nasa8x.messages.mustSelectItem);
                };
            },

            resetElement: function () {

                // Set class for button

                $('input:button,input:submit').addClass('button').hover(
                    function () {
                        $(this).addClass('button-over');
                    },
                    function () {
                        $(this).removeClass('button-over');
                    });


                //Set class for textbox input:file,
                $('input:text,input:password,textarea')
                        .addClass('input').focus(function () {
                            if (!$(this).hasClass('focus-no-addclass')) {
                                $(this).addClass('input-focus');
                            }
                        }).blur(function () {
                            $(this).removeClass('input-focus');
                        });
            },

            getQueryString: function (key) {
                key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var regex = new RegExp("[\\?&]" + key + "=([^&#]*)", 'ig');
                var qs = regex.exec(window.location.href);
                if (qs == null)
                    return '';
                else
                    return qs[1];

            },



            bookmark: function (title, url) {
                if (window.sidebar) { // Mozilla Firefox Bookmark
                    window.sidebar.addPanel(title, url, "");
                } else if (window.external) { // IE Favorite
                    window.external.AddFavorite(url, title);
                } else if (window.opera) { // Opera 7+
                    return false; // do nothing
                } else {
                    alert('Unfortunately, this browser does not support the requested action, please bookmark this page manually.');

                }
                return false;
            },




            autoReload: function () {
                if (this.minutePageRefresh > 1) {
                    window.setTimeout("window.location.reload()", this.minutePageRefresh * 60 * 1000);
                }

            },

            isEnter: function (event) {

                return ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13));

            },

            isImage: function (_fileUrl) {
                var _reg = new RegExp("(http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png|jpeg|bmp)", 'i');
                //var _reg = new RegExp("^[a-zA-Z0-9-_\.]+\.(jpg|gif|png)$", 'i');                
                if (_reg.test(_fileUrl))
                    return true;
                else
                    return false;
            },

            isFlash: function (_fileUrl) {
                var _reg = new RegExp("(http(s?):)|([/|.|\w|\s])*\.(?:swf)", 'i');
                //var _reg = new RegExp('^[a-zA-Z0-9-_\.]+\.(swf)$', 'i');
                if (_reg.test(_fileUrl))
                    return true;
                else
                    return false;
            },

            isYoutube: function (_fileUrl) {
                //var _reg = new RegExp("(http(s?):)|([/|.|\w|\s])*\.(?:swf)", 'i');
                var _reg = new RegExp('http://(?:\S+?youtube\S+)', 'i');
                if (_reg.test(_fileUrl))
                    return true;
                else
                    return false;
            },
            truncate: function (value, arg) {
                var value_arr = value.split(' ');
                if (arg < value_arr.length) {
                    value = value_arr.slice(0, arg).join(' ');
                }
                return value;
            },

            getYoutubeEmbed: function (_url, _w, _h, _fullscreen) {

                var _html = "<object width=\"" + _w + "\" height=\"" + _h + "\"><param name=\"movie\" value=\"" + _url + "\"></param>";
                _html += "<param name=\"allowFullScreen\" value=\"" + _fullscreen + "\"></param><param name=\"allowscriptaccess\" value=\"always\"></param>";
                _html += "<embed src=\"" + _url + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\"";
                _html += "allowfullscreen=\"" + _fullscreen + "\" width=\"" + _w + "\" height=\"" + _h + "\"></embed></object>";
                return _html;
            },



            logout: function () {

                this._overlay('show');
                var ht = document.getElementsByTagName("html");
                ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
                if (confirm($.Nasa8x.messages.logoutConfirm)) {
                    return true;
                }
                else {
                    ht[0].style.filter = "";
                    this._overlay('hide');
                    return false;

                }
            },
            addJs: function (_url) {

                var headID = document.getElementsByTagName("head")[0];
                var newScript = document.createElement("script");
                newScript.type = "text/javascript";
                newScript.src = _url;
                headID.appendChild(newScript);
            },

            addCss: function (_url) {

                var fileref = document.createElement("link");
                fileref.setAttribute("rel", "stylesheet");
                fileref.setAttribute("type", "text/css");
                fileref.setAttribute("href", _url);

                if (typeof fileref != "undefined")
                    document.getElementsByTagName("head")[0].appendChild(fileref);

            },

            newWindow: function (url, name, width, height) {
                var winX = 0;
                var winY = 0;
                var w = width > 0 ? width : screen.width * 0.8;
                var h = height > 0 ? height : screen.height * 0.8;

                winX = ($(window).width() - w) * .5;
                winY = ($(window).height() - h) * .5;
                window.open(url, name, 'scrollbars,resizable=no, width=' + w + ',height=' + h + ',left=' + winX + ',top=' + winY);
            },

            openFM: function (_target) {
                var _url = this.fileManagerUrl + '?returnId=' + _target + '&target=' + $('#' + _target).val();
                var _w = $(window).width() * .8;
                var _h = $(window).height() * .8;
                this.newWindow(_url, 'xfm', _w, _h);
            },

            remove: function (_id) {

                $(_id).fadeOut(500, function () {
                    $(this).remove();
                });
            },
            moveFirst: function (_id) {

                var clone = $(_id).clone();

                $(_id).fadeOut(500, function () {

                    var _f = ($(this).parent()).children(":first-child");
                    if (_f)
                        clone.insertBefore(_f).fadeIn(500);

                    $(this).remove();
                });


                //                $(_id).fadeOut(500, function () {

                //                    clone.insertBefore($(_target).children(":first-child")).fadeIn(500);

                //                    $(this).remove();
                //                });



            },


            showFileManager: function () {

                var f = {
                    url: $.Nasa8x.fileManagerUrl + '?returnFull=1',
                    width: screen.width * 0.8, // pixel
                    height: screen.height * 0.8
                };

                var a = {
                    inline: false, // only works if inlinepopups plugin is available
                    window: window
                };

                // Use TinyMCE window API
                if (window.tinymce && tinyMCE.activeEditor) {
                    a.editor = tinyMCE.activeEditor;
                    return tinyMCE.activeEditor.windowManager.open(f, a);
                }


                // Use jQuery WindowManager
                if (window.jQuery && jQuery.WindowManager)
                    return jQuery.WindowManager.open(f, a);


                return false;
            },


            Comment: {

                feedbackId: '#feedback',
                replyId: '#replyId',
                placeholder: null,
                show: function (_target) {

                    if (_target)
                        $(_target).hide();

                    this.placeholder = _target;

                    this.reply(0, _target);
                },
                reply: function (_Id, _targetId) {
                    var _boxId = this.feedbackId;
                    var _reply = this.replyId;
                    var _placeholder = this.placeholder;
                    var _target = _targetId;

                    if (_target == undefined) {
                        _target = '#reply_' + _Id;

                    };


                    $(_boxId).insertAfter(_target);
                    //$(_target).attr('rel', 1);
                    $(_boxId).fadeIn(500, function () {
                        $(_reply).val(_Id);
                        var _textbox = $(_boxId + ' textarea').focus().focusout(function () {
                            var _val = $.trim($(this).val()).replace(/\n/g, '');
                            if (_val === '') {
                                $(_boxId).hide();

                                if (_placeholder)
                                    $(_placeholder).show();

                            }
                        });

                        if ($.autogrow) {
                            _textbox.autogrow();
                        };
                    });

                },

                cancel: function () {

                    var _placeholder = this.placeholder;
                    $(this.feedbackId + ' textarea').val('');
                    $(this.feedbackId).fadeOut(function () {

                        if (_placeholder)
                            $(_placeholder).show();

                    });
                }

            },



            showActionArea: function () {
                $('#detail-actions-area-container').slideDown();
            },

            closeActionArea: function () {

                $('#detail-actions-area-container .child').attr('rel', 0);
                $('#detail-actions-area-container').slideUp();
            },

            share: function (title, url) {

                var _el = $('#shareIt');
                if (_el.attr('rel') != 1) {
                    _el.attr('rel', 1).show();
                    $.shareIt.show({ title: title, url: url });
                    this.showActionArea();
                }
                else {
                    _el.hide();
                    this.closeActionArea();
                }

            },

            report: function () {

                var _el = $('#reportIt');
                if (_el.attr('rel') != 1) {
                    _el.attr('rel', 1).show();
                    this.showActionArea();
                }
                else {
                    _el.hide(); this.closeActionArea();
                }


            },


            switchView: function (_v) {

                if (_v) {
                    //this.Cookie.remove('__view');
                    this.Cookie.add('__view', _v);
                }
                else {
                    _v = this.Cookie.get('__view');
                };

                if (!this.String.isNullOrEmpty(_v)) {
                    $('li.view-type').removeClass("actived");
                    $('#view-' + _v).addClass('actived');
                    $('#_listPanel').removeClass().addClass(_v + '-view');
                }


            },

            htmlEditor: function () {

                if ($("textarea.tinymce").length <= 0) return;

                var _toolbar1 = '';
                var _toolbar2 = '';
                var _toolbar3 = '';
                var _toolbar4 = '';
                var _plugins = '';
                var _pdw = false;

                var _xfm = this.xFileManager ? '$.MvcForum.xfilemanagerCallback' : '';

                $('textarea.tinymce').each(function (ele) {

                    var _id = $(this).attr('id');
                    var _mode = $(this).attr('mode');
                    if (_mode !== undefined) {
                        if (_mode == 'small') {
                            _toolbar1 = "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,image,fullscreen";
                            _toolbar2 = "";
                            _toolbar3 = "";
                            //_plugins = "tabfocus,advimage,advlink,emotions,inlinepopups,media,paste,directionality,visualchars,xhtmlxtras";
                            _plugins = "autolink,directionality,tabfocus,emotions,inlinepopups,media,paste,visualchars,xhtmlxtras,fullscreen";

                        }
                        else if (_mode == 'medium') {
                            _toolbar1 = "pdw_toggle,fontselect,fontsizeselect,forecolor,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,anchor,|,emotions,image,youtube,codehighlighting,|,preview,fullscreen";
                            _toolbar2 = "pastetext,styleprops,backcolor,formatselect,|,search,replace,|,bullist,numlist,outdent,indent,blockquote,|,sub,sup,|,ltr,rtl,|,cite,abbr,acronym,del,ins,attribs,|,charmap,iespell,advhr";
                            _toolbar3 = "";
                            _pdw = true;
                            _plugins = "pdw,tabfocus,table,advimage,advlink,emotions,inlinepopups,media,paste,directionality,visualchars,xhtmlxtras";
                        }

                    }
                    else {
                        _toolbar1 = "pdw_toggle,paste,pastetext,pasteword,|,undo,redo,cleanup,|,tablecontrols,|,hr,removeformat,visualaid,|,insertlayer,moveforward,movebackward,absolute";
                        _toolbar2 = "search,replace,|,bullist,numlist,outdent,indent,blockquote,|,sub,sup,|,ltr,rtl,|,cite,abbr,acronym,del,ins,attribs,|,charmap,emotions,iespell,advhr,|,image,media,|,code,preview,fullscreen";
                        _toolbar3 = "styleprops,forecolor,backcolor,fontselect,fontsizeselect,formatselect,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,anchor";
                        _toolbar4 = '';
                        _pdw = true;
                        _plugins = "pdw,tabfocus,pagebreak,style,layer,table,advhr,advimage,advlink,emotions,inlinepopups,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,advlist";
                    }

                    $(this).tinymce({
                        script_url: '/tiny_mce/tiny_mce.js',
                        skin: "cirkuit",
                        // General options
                        theme: "advanced",

                        plugins: _plugins,

                        // Theme options
                        theme_advanced_buttons1: _toolbar1,
                        theme_advanced_buttons2: _toolbar2,
                        theme_advanced_buttons3: _toolbar3,
                        theme_advanced_buttons4: _toolbar4,
                        theme_advanced_toolbar_location: "top",
                        theme_advanced_toolbar_align: "left",
                        theme_advanced_statusbar_location: "bottom",
                        theme_advanced_resizing: true,
                        remove_linebreaks: false,
                        paste_auto_cleanup_on_paste: true,
                        forced_root_block: false,
                        force_br_newlines: true,
                        force_p_newlines: false,
                        pdw_toggle_on: _pdw,
                        convert_urls: false,
                        pdw_toggle_toolbars: "2",
                        extended_valid_elements: "img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],object[classid|codebase|width|height],param[name|value],embed[src|quality|width|height|type|pluginspage|bgcolor]",


                        inlinepopups_skin: 'office2007blue',
                        tab_focus: ':prev,:next',
                        entity_encoding: "raw",
                        verify_html: false,


                        file_browser_callback: _xfm,

                        setup: function (ed) {
                            ed.onChange.add(function (ed) {
                                tinyMCE.triggerSave();
                            });


                        },


                        // Replace values for the template plugin
                        template_replace_values: {
                            username: "Nasa8x",
                            staffid: "118"
                        }
                    });


                });


            },



            editor: function () {

                $('.tinymce').tinymce({
                    //script_url: '/tiny_mce/tiny_mce.js',
                    script_url: '/tiny_mce/tiny_mce_gzip.axd',

                    skin: "cirkuit",
                    //skin_variant: "silver",
                    theme: "advanced",
                    plugins: "autolink,directionality,tabfocus,emotions,inlinepopups,paste,visualchars,xhtmlxtras,fullscreen",

                    // Theme options
                    theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,fontselect,fontsizeselect,undo,redo,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,imagex,fullscreen",
                    theme_advanced_buttons2: '',
                    theme_advanced_buttons3: '',
                    theme_advanced_buttons4: '',
                    theme_advanced_toolbar_location: "top",
                    theme_advanced_toolbar_align: "left",
                    theme_advanced_statusbar_location: "bottom",
                    theme_advanced_resizing: true,
                    paste_auto_cleanup_on_paste: true,
                    remove_linebreaks: false,
                    forced_root_block: false,
                    force_br_newlines: true,

                    force_p_newlines: false,
                    theme_advanced_resize_horizontal: false,
                    //convert_urls: false,
                    entity_encoding: "raw",
                    verify_html: false,
                    inlinepopups_skin: 'office2007blue',
                    tab_focus: ':prev,:next',

                    setup: function (ed) {
                        /*
                        ed.onChange.add(function (ed) {
                        tinyMCE.triggerSave();
                        });
                        */

                        ed.addButton('imagex', {
                            title: 'Chèn ảnh',
                            onclick: $.Nasa8x.showFileManager
                        });


                    },

                    // Replace values for the template plugin
                    template_replace_values: {
                        username: "Nasa8x",
                        staffid: "118"
                    }
                });


            },



            parseJsonToForm: function (json) {

                for (var key in json) {

                    var _elt = $('#' + key.toString().toLowerCase());
                    var _val = json[key];

                    if ($(_elt)) {
                        try {

                            if (_elt.is("input:text,input:password,input:hidden,textarea")) {
                                if (_val != null)
                                    _elt.val(_val);
                                else {
                                    _elt.val('');
                                }

                            }
                            else if (_elt.is('select')) {

                                if (_val != null && _elt.attr('multiple')) {
                                    var _vals = _val.split(',');
                                    if (_val.length > 0) {
                                        $.each(_vals, function (index, value) {
                                            _elt.find("option[value=" + value + "]").attr("selected", "selected");
                                        });
                                    }



                                }
                                else {

                                    _elt.find("option[value=" + _val + "]").attr("selected", "selected");

                                }



                            }
                            else if (_elt.is('input:checkbox,input:radio')) {
                                _elt.attr('checked', _val == true || _val == 1 ? true : false).val(_val);


                            }
                        }
                        catch (err) { }
                    }

                }
            },


            loadJson: function (_url) {

                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: '',
                    url: _url,
                    success: function (response) {
                        //alert(data.d);
                        var data = (typeof response) == 'string' ? eval('(' + response + ')') : response;

                        $.Nasa8x.parseJsonToForm(data);

                        if ($.fn.scrollTo) {

                            $($.Nasa8x.ajaxContainer).scrollTo(0, 300);
                        }
                        else {

                            $($.Nasa8x.ajaxContainer).animate({ scrollTop: 0 }, 300);


                        }

                    },
                    error: function (err) {

                        alert(err);

                    }

                });

            },

            ajaxSuccess: function (d) {


                if (d.Reload) {
                    window.location.reload();
                    return;

                }

                if (d.Alert) {

                    alert(d.Text);
                }

                else if (d.Text && d.Text.length > 1) {

                    $(d.TargetId).html(d.Text);

                    if (d.Inbox) {
                        $(d.TargetId).parent().fadeIn();
                    }

                    $(d.TargetId).scrollTo(0, 300);

                }


                if (d.ReturnUrl && d.ReturnUrl.length > 2)
                    window.location = d.ReturnUrl;

                if (d.Callback) {
                    eval(d.Callback);
                }

            },

            ajaxLoad: function (_url, _target) {

                //window.location.replace(_url);

                this.showLoading();

                if (_target) {
                    $(_target).load(_url, function () {
                        $.Nasa8x.hideLoading();
                        $.Nasa8x.htmlEditor();

                        if ($.fn.scrollTo) {

                            $(_target).scrollTo(0, 300);
                        }

                    });
                }
                else {
                    $(this.ajaxContainer).load(_url, function () {
                        $.Nasa8x.hideLoading();
                        $.Nasa8x.htmlEditor();

                    });
                }
            },

            ajaxSubmit: function (formId, callback) {


                if (window.tinymce && $("textarea.tinymce")) {
                   window.tinyMCE.triggerSave();
                };



                var _f = formId ? $('#' + formId) : $(document.forms[0]);


                var _validate = _f.validate({ meta: 'validate', invalidHandler: function () { $(this).find(":input.error:first").focus(); } });

                if (_validate.form()) {

                    this.showLoading();

                    _f.find(":password").each(function () {
                        var _v = $(this).val();
                        $(this).val($.Nasa8x.Hash.sha256(_v));
                    });

                    _f.find(":checkbox").each(function () {
                        $(this).val($(this).is(":checked"));
                    });


                    if (_f.attr("fvalid") != "1") {
                        _f.attr("fvalid", "1");
                        _f.append('<input type="hidden" value="1" name="fvalid" /><input type="hidden" value="1" name="ajax" />');

                    };

                    $.post(
                    _f.attr("action"),
                    _f.serialize(),
                    function (msg) {

                        if (callback) {
                            if ($.isFunction(callback))
                                callback.apply();
                            else
                                eval(callback);
                        }
                        else {

                            $.Nasa8x.ajaxSuccess(msg);

                        };


                    }).
                    error(function (xhr, ajaxOptions, thrownError) {
                        alert('Error:' + xhr.status + '\n' + thrownError);
                        //alert(thrownError);

                    }).complete(function () {

                        _f.find("input:password").val('');
                        $.Nasa8x.hideLoading();


                    });

                } // end validate

            },

             cmd: function (c,callback) {

                 $("#cmd").val(c);

                 this.ajaxSubmit('_fcmd',callback);
             },
            
            /*
            cmd: function (url, data, callback) {

                this.showLoading();

                $.post(
                    url,
                    data,
                    function (msg) {

                        if (callback) {
                            if ($.isFunction(callback))
                                callback.apply();
                            else
                                eval(callback);
                        }
                        else {

                            $.Nasa8x.ajaxSuccess(msg);

                        };


                    })
                   .complete(function () {

                       $.Nasa8x.hideLoading();

                   })
                    .error(function (xhr, ajaxOptions, thrownError) {
                        alert('Error:' + xhr.status + '\n' + thrownError);

                    });

            },
            */

            onLoad: function () {
                this.resetElement();
                this.hideLoading();

            },


            onPageLoad: function () {


                this.Environment.init();

                this.switchView();

            }
            // add more function

        }// end Nasa8x
    });   // end extend

})(jQuery);




jQuery.extend($.Nasa8x.messages, {

    insert: "Save",
    update: "Update",
    edit: 'Save',
    cancel: "Hủy bỏ",
    mustSelectItem: 'You must select one item for action',
    deleteItemsConfirm: 'Are you sure want to delete {0} items',
    deleteOneConfirm: 'Are you sure want to delete this item',
    logoutConfirm: 'Bạn có chắc chắn muốn thoát khỏi hệ thống?'

});


jQuery.extend(jQuery.validator.messages, {
    required: "*", //Không được bỏ trống
    remote: "Please fix this field.",
    email: "Vui lòng nhập đúng địa chỉ email.",
    url: "Vui lòng nhập đúng URL.",
    date: "Please enter a valid date.",
    dateISO: "Please enter a valid date (ISO).",
    dateDE: "Bitte geben Sie ein gültiges Datum ein.",
    number: "Vui lòng nhập đúng số [0-9].",
    numberDE: "Bitte geben Sie eine Nummer ein.",
    digits: "Vui lòng nhập giá trị >=0",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "Nhập giá trị không trùng hợp. Xin vui lòng nhập lại.",
    accept: "Please enter a value with a valid extension.",
    maxlength: $.format("Không nhập quá {0} ký tự."),
    minlength: $.format("Vui lòng nhập ít nhất {0} ký tự."),
    rangelength: $.format("Vui lòng nhập trong khoảng {0} đến {1} ký tự."),
    range: $.format("Vui lòng nhập giá trị trong khoảng {0} và {1}."),
    max: $.format("Vui lòng nhập giá trị nhỏ hơn: {0}."),
    min: $.format("Không nhập giá trị lớn hơn: {0}.")
});


